package cn.edu.uestc.smgt.controller.manager;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.edu.uestc.smgt.common.QueryBase;
import cn.edu.uestc.smgt.pojo.AssistStudent;
import cn.edu.uestc.smgt.pojo.Unit;
import cn.edu.uestc.smgt.service.AssistStudentService;
import cn.edu.uestc.smgt.util.ExcelUtil;
import cn.edu.uestc.smgt.util.LoginUtil;

@Controller
@RequestMapping("/aststu/")
public class AssistStudentController {
	@Autowired
	private AssistStudentService assistStudentService;

	/**
	 * 条件查询所有助管
	 * 
	 * @param map
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("listBySelection")
	@ResponseBody
	public Object listBySelections(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@RequestParam HashMap map) throws IOException {
		return assistStudentService.getAllAssStu(map);
	}

	@RequestMapping("listBySelectionAndPage")
	@ResponseBody
	public Object listBySelectionsAndPage(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@RequestParam HashMap map) throws IOException {
		QueryBase querybase = new QueryBase();
		querybase.addParameter("id", map.get("id"));
		querybase.addParameter("name", map.get("name"));
		querybase.addParameter("unitId", map.get("unitId"));
		querybase.setPageSize(Long.parseLong(map.get("rows").toString()));
		querybase.setCurrentPage(Long.parseLong(map.get("page").toString()));
		assistStudentService.query(querybase);
		HashMap result = new HashMap();
		result.put("total", querybase.getTotalRow());
		result.put("rows", querybase.getResults());
		return result;
	}

	/**
	 * 添加一条助管信息
	 * 
	 * @param as
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("add")
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response,
			HttpSession session, @ModelAttribute AssistStudent as)
			throws IOException {
		String message;
		int status = assistStudentService.add(as);
		if (status == 1) {
			message = "添加成功";
		} else {
			message = "添加失败";
		}
		HashMap result = new HashMap();
		result.put("message", message);
		result.put("status", status);
		return result;
	}

	/**
	 * 修改记录
	 * 
	 * @param unit
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("update")
	@ResponseBody
	public Object update(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@ModelAttribute AssistStudent as) throws IOException {

		String message;
		int status = assistStudentService.update(as);
		if (status == 1) {
			message = "修改成功";
		} else {
			message = "修改失败";
		}
		HashMap result = new HashMap();
		result.put("message", message);
		result.put("status", status);
		return result;
	}

	/**
	 * 删除一条记录
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("delete")
	@ResponseBody
	public Object delete(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@RequestParam String id) throws IOException {
		String message;
		int status = assistStudentService.delete(id);
		if (status == 1) {
			message = "删除成功";
		} else {
			message = "删除失败";
		}
		HashMap result = new HashMap();
		result.put("message", message);
		result.put("status", status);
		return result;
	}

	/**
	 * 批量删除
	 * 
	 * @throws IOException
	 */
	@RequestMapping("deleteSelections")
	@ResponseBody
	public Object deleteSelections(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@RequestParam String ids) throws IOException {
		System.out.println(ids);
		String[] idArray = ids.split(",");
		System.out.println(Arrays.deepToString(idArray));
		String message;
		int status = assistStudentService.deleteMany(idArray);
		if (status == 1) {
			message = "删除成功";
		} else {
			message = "删除失败";
		}
		HashMap result = new HashMap();
		result.put("message", message);
		result.put("status", status);
		return result;
	}

	/**
	 * 批量上传文件
	 * 
	 * @throws IOException
	 */
	@Transactional(rollbackFor = { Exception.class })
	@RequestMapping("upload")
	@ResponseBody
	public Object upload(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@RequestParam("uploadExcel") CommonsMultipartFile files)
			throws IOException {
		System.out.println(files.getOriginalFilename());
		HashMap ret = new HashMap();
		int fileSize = 0;
		if (files != null) {
			int rowNum = 0;
			try {
				// 将excel文件转为List，然后调用service层方法批量插入
				InputStream is = files.getInputStream();
				HashMap sheetMap = ExcelUtil.getSheet(is, 1);
				if (sheetMap.get("sheet") != null) {
					Sheet sheet = (Sheet) sheetMap.get("sheet");
					List list = readAststuData(sheet);
					if (null != list)
						fileSize = list.size();
					// 导入数据，如果有已经存在数据库中的数据则不导入
					for (int i = 0; i < list.size(); i++) {
						HashMap map = (HashMap) list.get(i);
						rowNum = ((Integer) map.get("row")).intValue();
						assistStudentService.addWithMap(map);
					}
				} else {
					ret.put("message", "数据为空");
					return ret;
				}
				is.close();
			} catch (Exception e1) {
				e1.printStackTrace();
				if (rowNum == fileSize + 1) {
					ret.put("message", "导入数据成功");
					return ret;
				} else {
					ret.put("message", "第" + rowNum + "行数据异常，请检查！");
					return ret;
				}
			}
			ret.put("message", "导入数据成功");
			return ret;
		} else {
			ret.put("message", "未选择文件！");
			return ret;
		}

	}

	/**
	 * 将excel转为list
	 * 
	 * @param sheet
	 * @return
	 */
	private List readAststuData(Sheet sheet) {
		// TODO Auto-generated method stub
		List list = new ArrayList();
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			HashMap map = new HashMap();
			int j = 0;
			int nullCount = 0;
			String id = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(id)) {
				map.put("id", id);
			} else {
				nullCount++;
			}
			String name = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(name)) {
				map.put("name", name);
			} else {
				nullCount++;
			}
			String unitId = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(unitId)) {
				map.put("unitId", unitId);
			} else {
				nullCount++;
			}
			String officeName = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(officeName)) {
				map.put("officeName", officeName);
			} else {
				nullCount++;
			}
			String tel = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(tel)) {
				map.put("tel", tel);
			} else {
				nullCount++;
			}
			String bankNo = ExcelUtil.getCellValue(sheet, j++, i);
			if (!ExcelUtil.isNullOrEmpty(bankNo)) {
				map.put("bankNo", bankNo);
			} else {
				nullCount++;
			}
			if (nullCount != j) {
				map.put("row", Integer.valueOf(i + 1));
				list.add(map);
			}
		}
		return list;
	}

}
